package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.service.ICourseCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-06-22
 */
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements ICourseCategoryService {

    @Autowired
    CourseCategoryMapper courseCategoryMapper;

    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
        //将list转map,以备使用,排除根节点
        Map<String, CourseCategoryTreeDto> maptemp = courseCategoryTreeDtos.stream()
                .filter(courseCategory -> !id.equals(courseCategory.getId()))
                .collect(Collectors.toMap(CourseCategoryTreeDto::getId, value -> value, (key1, key2) -> key2));
        //最终返回的list
        List<CourseCategoryTreeDto> courseCategoryDtos = new ArrayList<>();
        //依次遍历每个元素,排除根节点
        courseCategoryTreeDtos.stream()
                .filter(category -> !id.equals(category.getId()))
                .forEach(category -> {
                    if(id.equals(category.getParentid()))
                    {
                        courseCategoryDtos.add(category);
                    }
                    CourseCategoryTreeDto parentNode = maptemp.get(category.getParentid());
                    if(parentNode != null){
                        if(parentNode.getChildrenTreeNodes() == null){
                            parentNode.setChildrenTreeNodes(new ArrayList<>());
                        }
                        parentNode.getChildrenTreeNodes().add(category);
                    }
                });

        return courseCategoryDtos;
    }
}
